package cn.visu.security.filter;


import cn.visu.bean.User;
import com.visu.Constants;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义授权器
 * 用来决定主体是否有权限进行相应的操作
 */
public class MyPermissionAuthorizationFilter extends AuthorizationFilter {

    /**
     * 判断是否可以访问
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        HttpServletRequest var2 = WebUtils.toHttp(request);

        String method = var2.getMethod();

        String str = var2.getHeader("Access-Control-Request-Headers");
        if (method.equals("OPTIONS")) {
            if ("authentication".equals(str)) {
                WebUtils.toHttp(response).setStatus(202);
                return true;
            }
        }
        Subject subject = this.getSubject(request, response);
        User user = (User) subject.getSession().getAttribute("user");
        if (user != null && user.getType() == 1) {
            return true;
        }
        String[] perms = (String[]) ((String[]) mappedValue);
        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else if (!subject.isPermittedAll(perms)) {
                isPermitted = false;
            }
        }

        return isPermitted;
    }

    /**
     * 非法访问的处理
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        WebUtils.toHttp(response).sendError(Constants.NO_PERMISSION, Constants.ERROR_PERM_MSG);
        return false;
    }
}
